$NG.AllReady(function (
	page,
	{
		useDataIndexChange,
		useValuesChange,
		useUpdateRows,
		useBeforeClick,
		useUpdateRow,
	}
) {
	// 编辑页面逻辑
	const mstform = $NG.getCmpApi("p_form_employ_apply");
	console.log(mstform, "mstform");
	const grid = $NG.getCmpApi("p_form_employ_apply_d");
	// 编码到名称的映射
	const employmentTypeMapping = {
		"01": "实施外包用工",
		"02": "研发二次开发用工",
	};
	const personnelcategoryMapping = {
		"01": "合同履约人员",
		"02": "项目用工",
		"03": "研发二次开发用工",
	};

	{
		//表头字段变化逻辑
		useValuesChange(({ args }) => {
			var u_yg_typer = mstform.getItem("u_yg_typer").getValue();
			console.log(u_yg_typer, "u_yg_typer");
			var grid = $NG.getCmpApi("p_form_employ_apply_d");
			console.log(grid, "grid");
			var data = grid.getData();
			// 将编码转换为名称
			var employmentTypeName = employmentTypeMapping[u_yg_typer] || u_yg_typer;
			data.forEach(function (item) {
				item.u_employment_type = u_yg_typer;
				item.u_employment_type_EXName = employmentTypeName; // 添加转换后的名称
				gridhandle(item);
			});
			grid.updateRow(data);
			console.log(`测试`, mstform.getItem("u_yg_typer").getValue());
			const _arr =["u_name","u_sex","idno","u_contact","u_age","u_graduatedschool","u_major","u_worklife","u_company","u_cntstart_dt_new","u_cntend_dt_new","u_real_dt"]
				console.log(`隐藏`);
				$NG.updateUI((updater) => {
					//【注意这里的表名不能为控件ID，必须要是表名】
					console.log(`吟唱`, updater);
					const _row = grid.getRows()
					_arr.forEach(element => {
						updater.editGrid.p_form_employ_apply_d[element].setProps(
							(e) => {
								if (mstform.getItem("u_yg_typer").getValue() == "02") {
									_row.forEach(item => {
										item[element] = null
									});
									grid.refreshView()
									return {
										...e, editor:
										{
											...e.editor,
											hidden: true,   //隐藏
											disabled: true
										}
									}
								} else {
									return {
										...e, editor:
										{
											...e.editor,
											hidden: false,   //隐藏
											disabled: false
										}
									}
								}
								
							}
						);
					});
				});
				grid.refreshView()
		}, "p_form_employ_apply.u_yg_typer");
		useValuesChange(({ args }) => {
			var phid_pc = mstform.getItem("phid_pc").getValue();
			var pc = mstform.getItem("phid_pc").getRawValue();
			var grid = $NG.getCmpApi("p_form_employ_apply_d");
			var data = grid.getData();
			data.forEach(function (item) {
				item.phid_pc = phid_pc;
				item.phid_pc_EXName = pc;
			});
			grid.updateRow(data);
		}, "p_form_employ_apply.phid_pc");
	}
	{
		//明细订阅字段编辑

		useDataIndexChange(({ args, instance }) => {
			const record = args[0];
			gridhandle(record);
			instance.updateRow(args[0]);
		}, "u_personnel_category");
		useDataIndexChange(({ args, instance }) => {
			const record = args[0];
			gridhandle(record);
			instance.updateRow(args[0]);
		}, "u_employment_type");
	}

	// 表体数据变化（增行、删行、引入）时，汇总计算至表头
	useUpdateRows(({ args }) => {
        console.log('监听表', args);
		var sumAmt = 0;
		const rows = args[0];
		isOne(rows)
		rows.forEach((items) => {
			if (items.u_amt) {
				sumAmt += parseFloat(items.u_amt);
			}
		});
		// 汇总赋值
		$NG.updateState((updater) => {
			updater.data.p_form_employ_apply.setProps({
				u_total_amt: sumAmt,
			});
		});
	}, "p_form_employ_apply_d");


	useDataIndexChange(
		({ args, table }) => {
			var gridTab = $NG.getCmpApi("p_form_employ_apply_d");
			var row = args[0];
			var u_amt = args[0].u_amt;
			var u_salary_ceiling = args[0].u_salary_ceiling;
			// if ((u_amt - u_salary_ceiling - 48) > '0') {
			//     row.u_isoverproof = {
			//         label: "是",
			//         value: "1"
			//     }
			// }
			// else {
			//     row.u_isoverproof = {
			//         label: "否",
			//         value: "0"
			//     }
			// }
			console.log("args表体数据", "args表体数据");
			if (u_amt - u_salary_ceiling - 48 > "0") {
				row.u_isoverproof = "1";
			} else {
				row.u_isoverproof = "0";
			}

			gridTab.updateRow(row); // 更新当前行数据
			gridTab.refreshView();
		},
		"u_amt",
		"u_position"
	); //监听的变化的字段

	// useUpdateRow(({ args, table }) => {
	// 	const record = args[0];
	// 	var idno = record.idno;
	// 	if (record.idno) {
	// 		validateIdCard(idno);
	// 	}
	// 	// tables.updateRow(record);
	// }, "p_form_employ_apply_d");
	function debounce(fn, delay) {
		//防抖
		let timer = null;
		return function () {
			if (timer) {
				clearTimeout(timer);
			}
			timer = setTimeout(() => {
				fn.apply(this, arguments);
				timer = null;
			}, delay);
		};
	}
	useUpdateRow(({ args, table }) => {
		const record = args[0];
		console.log("123123123123", record);
		const { u_qualification_grade1, u_position, u_residence } = record;

		var idno = record.idno;
		if (idno) {
			// 获取 name 为 "idno" 的第一个输入框元素
			var idCardInput = document.getElementsByName("idno")[0];
			// 每次失去焦点时触发校验
			idCardInput?.addEventListener("blur", async function () {
				const idCard = idCardInput.value;
				const isValid = validateIdCard(idCard);
				if (isValid) {
					// 校验通过，执行其他逻辑
					console.log("身份证号合法");
				} else {
					record.idno = "不合法身份证请重新输入";
				}
			});
		}
		// console.log(u_qualification_grade, u_position, u_residence, "打印的值");
		console.log(
			[110100, 440100, 310100, 440300].includes(u_residence) ? "01" : "02",
			"调试"
		);
		if (u_qualification_grade1 && u_position && u_residence) {
			console.log(
				u_qualification_grade1,
				u_position,
				[110100, 440100, 310100, 440300].includes(u_residence) ? "01" : "02"
			);

			$NG.execServer(
				"getPriceTop",
				{
					qg: u_qualification_grade1,
					pe: u_position,
					cc: [110100, 440100, 310100, 440300].includes(u_residence)
						? "01"
						: "02",
				},
				function (res) {
					console.log("测试获取薪资上线",res);
					const data = JSON.parse(res.data);
					const PriceTop = data[0].extendObjects.u_sal_limit_standard;
					console.log(PriceTop, "222222");
					if (PriceTop) {
						record.u_salary_ceiling = PriceTop;
					} else {
						record.u_salary_ceiling = "未查询到数据";
					}
					$NG.updateState((updater) => {
						updater.data.p_form_employ_apply.setProps({
							u_bu: { value: zz, label: zz_oname },
							u_product_line: { value: cpx, label: cpx_name },
							u_xmjl: { value: xmjl, label: xmjl_name },
							u_regional_center: { value: qyzx, label: qyzx_name },
							u_pc_no: pc_no,
						});
					});
					grid.refreshView();
				}
			);
		} else {
			record.u_salary_ceiling = "";
					grid.refreshView();
		}

		console.log(record, "record");
	}, "p_form_employ_apply_d");
	// 项目名称变化时自动带入产品线、事业部
	useValuesChange(({ args }) => {
		console.log(args[0], "aaaa1111");
		const phid_pc = args[0].phid_pc.value;
		if (phid_pc) {
			console.log(phid_pc);
			$NG.execServer("getProjInfo", { pc: phid_pc }, function (res) {
				const data = JSON.parse(res.data);
				const zz = data[0].extendObjects.zz;
				const zz_oname = data[0].extendObjects.oname;
				const cpx = data[0].extendObjects.cpx;
				const cpx_name = data[0].extendObjects.cname;
				const xmjl = data[0].extendObjects.xmjl;
				const xmjl_name = data[0].extendObjects.xmjl_name;
				const qyzx = data[0].extendObjects.qyzx;
				const qyzx_name = data[0].extendObjects.qyzx_name;
				const pc_no = data[0].extendObjects.pc_no;

				$NG.updateState((updater) => {
					updater.data.p_form_employ_apply.setProps({
						u_bu: { value: zz, label: zz_oname },
						u_product_line: { value: cpx, label: cpx_name },
						u_xmjl: { value: xmjl, label: xmjl_name },
						u_regional_center: { value: qyzx, label: qyzx_name },
						u_pc_no: pc_no,
					});
				});
			});
		}
	}, "p_form_employ_apply.phid_pc");

	// 添加行前的处理
	useBeforeClick(async function ({ args }) {
		try {
			// 获取表单字段值
			var u_yg_typer = mstform.getItem("u_yg_typer").getValue();
			var yg_type = mstform.getItem("u_yg_typer").getRawValue();
			var phid_pc = mstform.getItem("phid_pc").getValue();
			var pc = mstform.getItem("phid_pc").getRawValue();

			// 将编码转换为名称
			var employmentTypeName = employmentTypeMapping[u_yg_typer] || u_yg_typer;

			// 检查 grid 是否已定义
			if (!grid) {
				console.error("Grid is not defined");
				return false; // 取消向下执行
			}

			// 添加行到网格
			grid.addRows({
				u_employment_type: u_yg_typer,
				u_employment_type_EXName: employmentTypeName, // 添加转换后的名称
				phid_pc: phid_pc,
				phid_pc_EXName: pc,
			});

			// 刷新视图
			if (typeof grid.refreshView === "function") {
				grid.refreshView();
			} else {
				console.error("refreshView method is missing on grid");
			}

			return false; // 取消向下执行
		} catch (error) {
			console.error("Error in useBeforeClick:", error);
			return false; // 取消向下执行
		}
	}, "addrow");

	function gridhandle(record) {
		if (mstform.getItem("u_yg_typer").getValue() == "02") {
			$NG.updateUI((updater) => {
				updater.editGrid.p_form_employ_apply_d.u_personnel_category.setProps(
					{
						disabled: true, //只读
					}
				);
			});
			record.u_personnel_category = "03";
			record.u_personnel_category_EXName = "研发二次开发用工";
		} else {
			$NG.updateUI((updater) => {
				updater.editGrid.p_form_employ_apply_d.u_personnel_category.setProps({
					disabled: false, //只读
				});
			});
			if (record.u_personnel_category == "03") {
				record.u_personnel_category = "";
				record.u_personnel_category_EXName = "";
				// $NG.alert("用工类型选择了实施外包用工，人员类别只能选合同履约人员和项目用工");
			}
		}
	}
});
function validateIdCard(idCard) {
	// 首先将输入的身份证号码统一转换为大写形式，方便后续校验和比较，避免大小写不一致导致的问题
	idCard = idCard.toUpperCase();

	// 定义错误信息数组，用于收集校验过程中发现的所有错误信息
	const errors = [];

	// 1. 长度校验
	if (idCard.length !== 18) {
		errors.push("身份证号长度必须为18位");
		return false;
	}

	// 2. 整体格式校验，确保每一位都是合法字符（前17位为数字，第18位为数字或者X）
	for (let i = 0; i < idCard.length; i++) {
		const char = idCard.charAt(i);
		if (i < 17 && isNaN(parseInt(char))) {
			// 前17位中如果出现非数字字符，直接判定为非法输入
			errors.push("身份证号前17位必须全部为数字");
			return false;
		}
		if (i === 17 && char !== "X" && isNaN(parseInt(char))) {
			// 第18位如果不是数字也不是X，判定为非法输入
			errors.push("身份证号第18位必须是数字或者X");
			return false;
		}
	}

	// 3. 地区代码校验（这里简单校验前6位是否为数字，实际应用中应该和标准地区代码库比对）
	const areaCode = idCard.substring(0, 6);
	if (!/^\d{6}$/.test(areaCode)) {
		errors.push("身份证号前6位地区代码不合法");
		return false;
	}

	// 4. 出生日期校验
	const birthYear = parseInt(idCard.substring(6, 10), 10);
	const birthMonth = parseInt(idCard.substring(10, 12), 10);
	const birthDay = parseInt(idCard.substring(12, 14), 10);

	// 校验年份范围是否合理（简单判断在合理区间内，实际应用可根据业务需求细化）
	if (birthYear < 1900 || birthYear > new Date().getFullYear()) {
		errors.push("身份证号中的出生年份不合法");
		return false;
	}

	// 校验月份范围是否合理（1 - 12月）
	if (birthMonth < 1 || birthMonth > 12) {
		errors.push("身份证号中的出生月份不合法");
		return false;
	}

	// 根据月份判断该月最大天数，校验日期是否合理
	const monthDays = [
		31,
		28 +
			((birthYear % 4 === 0 && birthYear % 100 !== 0) || birthYear % 400 === 0
				? 1
				: 0),
		31,
		30,
		31,
		30,
		31,
		31,
		30,
		31,
		30,
		31,
	];
	if (birthDay < 1 || birthDay > monthDays[birthMonth - 1]) {
		errors.push("身份证号中的出生日期不合法");
		return false;
	}

	// 创建日期对象来再次验证日期的合法性（考虑边界情况等）
	const date = new Date(birthYear, birthMonth - 1, birthDay);
	if (
		date.getFullYear() !== birthYear ||
		date.getMonth() + 1 !== birthMonth ||
		date.getDate() !== birthDay
	) {
		errors.push("身份证号中的出生日期不合法");
		return false;
	}

	// 5. 校验码校验
	const weightFactors = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
	const checkCodes = ["1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"];

	let sum = 0;
	for (let i = 0; i < 17; i++) {
		sum += parseInt(idCard.charAt(i), 10) * weightFactors[i];
	}

	const checkCode = checkCodes[sum % 11];
	if (idCard.charAt(17) !== checkCode) {
		errors.push("身份证号校验码不正确");
		return false;
	}

	// 如果所有校验都通过，说明身份证号合法
	console.log("身份证号合法");
	return true;
}

// 人员类别和用工类别唯一且细节判断
function isOne(arr){
	try{
		arr.forEach(item => {
			if(item.u_employment_type.split(",").length > 1) {
				item.u_employment_type = item.u_employment_type.split(",")[0]
				item.u_employment_type_EXName = item.u_employment_type_EXName.split(",")[item.u_employment_type_EXName.split(",").length-1]
			} else if(item.u_personnel_category.split(",").length >1){
				if(item.u_employment_type_EXName == "实施外包用工" || item.u_employment_type == '01'){
					item.u_personnel_category = item.u_personnel_category.split(",")[item.u_personnel_category.split(",").length-1]
					item.u_personnel_category_EXName = item.u_personnel_category_EXName.split(",")[item.u_personnel_category_EXName.split(",").length-1]
					if (item.u_personnel_category == "03" || item.u_personnel_category_EXName == "研发二次开发用工") {
						item.u_personnel_category = ""
						item.u_personnel_category_EXName = ""
					}
				} else {
					item.u_personnel_category = item.u_personnel_category.split(",")[item.u_personnel_category.split(",").length-1]
					item.u_personnel_category_EXName = item.u_personnel_category_EXName.split(",")[item.u_personnel_category_EXName.split(",").length-1]
				}
			}
		})
			
		
			$NG.getCmpApi("p_form_employ_apply_d").refreshView()
	} catch(er){}
}
// select p.phid_org syb, fg.oname oname , p.user_product_line cpx, s.c_name cname, p.bill_no pc_no, p.project_manager xmjl, he.bill_name xmjl_name from project_table p left join fg_orglist fg on fg.phid=p.phid_org left join fg_simple_data s on s.phid=p.user_product_line left join hr_epm_main he on he.phid=p.project_manager where p.phid=@pc

// select p.u_position gangwei,p.u_residence ,p.u_qualification_grade zizhidengji where p.phid=@pc
